﻿function getToken() {
    return localStorage.getItem('token');
}

async function post(url, data) {
    const token = getToken();
    const headers = {
        'Content-Type': 'application/json'
    };
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(data)
        });
        if (!response.ok) {
            alert(`HTTP error! Status: ${response.status}`);
            return;
        }
        var json = await response.json();
        if (json) {
            if (json.code == 'success') {
                return json;
            } else {
                alert(json.msg);
            }
        }
        return json;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    }
}

// 封装 GET 请求
async function get(url) {
    const token = getToken();
    const headers = {};

    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }

    try {
        const response = await fetch(url, {
            method: 'GET',
            headers: headers
        });
        if (!response.ok) {
            alert(`HTTP error! Status: ${response.status}`);
            return;
        }
        var json = await response.json();
        if (json) {
            if (json.code == 'success') {
                return json;
            } else {
                alert(json.msg);
            }
        }
        return json;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    }
}